package com.UnionPayCenter.vastchain;

import com.UnionPayCenter.entity.ShopInfoEntity;
import com.UnionPayCenter.entity.UserEntity;
import com.UnionPayCenter.exception.ApiException;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.math.BigDecimal;

import static java.math.BigDecimal.valueOf;

/**
 * @program: UnionPayServers
 * @description: 微信支付
 * @author: bite
 * @create: 2019-06-05 11:27
 **/
@Slf4j
public class WechatPayUtil {
    private static MediaType MEDIA_TYPE = MediaType.parse("application/json");
    /*
        post方式
     */
    private static final String METHOD_POST = "POST";
    /*
        创建预支付单url
     */
    private static final String SUBMERCHANT_PAY_URL = "https://v1.api.tc.vastchain.ltd/submerchant-pay/";
    /*
        创建微信小程序支付 url
     */
    private static final String WECHATPAY_URL ="https://v1.api.tc.vastchain.ltd/submerchant-pay/wechatPay";
    /*
        创建银联支付 url
     */
    private static final String WECHATUNIONPAYBIZSMALL_URL ="https://v1.api.tc.vastchain.ltd/submerchant-pay/wechatUnionPayBizSmall";

    /**
     * @Description: 微信支付下单
     * @Param:
     *          shopInfo：商铺配置信息 ShopService - wechatPayGetShopInfo() 获取
     *          user：会员信息 UserService - wechatPayGetUser() 获取
     *          orderId： 订单号
     *          price：价格（分）
     *          desc：商品或支付单简要描述
     * @return:
     * @Author: bite
     * @Date: 2019/6/1
     */
    public static JSONObject pay(ShopInfoEntity shopInfo, UserEntity user, String orderId, int price, String desc) throws Exception {

        JSONObject extraInfo = new JSONObject();
        extraInfo.put("body", desc);

        BigDecimal bigDecimal = valueOf(price).divide(new BigDecimal(100));
        if(bigDecimal.compareTo(BigDecimal.ZERO) != 1){
            throw new ApiException(-1, String.format("创建预支付单失败, 金额：%s", price));
        }
        //创建预支付单
        JSONObject body = new JSONObject();
        body.put("subMerchantId", shopInfo.getYlMerchant()); //"发起支付的子商户号"
        body.put("totalAmount", bigDecimal.toString());//"交易金额"
        body.put("orderId", orderId);//交易所关联的订单号
//        body.put("extraInfo", extraInfo);//该交易所关联的额外信息，可以任意设置，建议使用 JSON 格式
        body.put("extraInfo", null);

        OkHttpClient client = new OkHttpClient();
        Request.Builder request = new Request.Builder();
        request = request.post(RequestBody.create(MEDIA_TYPE, body.toJSONString()));

        Request build = request.url(SUBMERCHANT_PAY_URL).build();

        Response response = client.newCall(build).execute();

        String res = response.body().string();
        log.info("SUBMERCHANT_PAY response {}", res);
        JSONObject jsonObject = JSONObject.parseObject(res);
        String status = jsonObject.getString("status");
        if (status.equals("success")) {
            String prepayId = jsonObject.getString("prepayId");

            //创建微信小程序支付
            JSONObject body1 = new JSONObject();
            body1.put("prepayId", prepayId);
            body1.put("openId", user.getOpenid());

            OkHttpClient client1 = new OkHttpClient();
            Request.Builder request1 = new Request.Builder();
            request1 = request1.post(RequestBody.create(MEDIA_TYPE, body1.toJSONString()));

            Request build1 = request1.url(WECHATPAY_URL).build();

            Response response1 = client1.newCall(build1).execute();

            String res1 = response1.body().string();
            log.info("WECHATPAY response {}", res1);
            JSONObject jsonObject1 = JSONObject.parseObject(res1);
            String status1 = jsonObject1.getString("status");
            if (status1.equals("success")) {
                JSONObject returnJson = new JSONObject();
                returnJson.put("prepayId", prepayId);
                returnJson.put("return", jsonObject1.getJSONObject("args"));
                return returnJson;
            }
            throw new ApiException(-1, String.format("创建微信小程序支付失败, %s", jsonObject1.getString("msg")));
        }
        throw new ApiException(-1, "创建预支付单失败");
    }

    /**
     * @Description: 银联支付下单
     * @Param:
     *          shopInfo：商铺配置信息 ShopService - wechatPayGetShopInfo() 获取
     *          user：会员信息 UserService - wechatPayGetUser() 获取
     *          orderId： 订单号
     *          price：价格（分）
     *          desc：商品或支付单简要描述
     * @return:
     * @Author: bite
     * @Date: 2019/6/29
     */
    public static JSONObject unionPay(ShopInfoEntity shopInfo, UserEntity user, String orderId, int price, String desc) throws Exception {

        JSONObject extraInfo = new JSONObject();
        extraInfo.put("body", desc);

        BigDecimal bigDecimal = valueOf(price).divide(new BigDecimal(100));
        if(bigDecimal.compareTo(BigDecimal.ZERO) != 1){
            throw new ApiException(-1, String.format("创建银联预支付单失败, 金额：%s", price));
        }
        //创建银联预支付单
        JSONObject body = new JSONObject();
        body.put("subMerchantId", shopInfo.getYlMerchant()); //"发起支付的子商户号"
        body.put("totalAmount", bigDecimal.toString());//"交易金额"
        body.put("orderId", orderId);//交易所关联的订单号
//        body.put("extraInfo", extraInfo);//该交易所关联的额外信息，可以任意设置，建议使用 JSON 格式
        body.put("extraInfo", null);

        OkHttpClient client = new OkHttpClient();
        Request.Builder request = new Request.Builder();
        request = request.post(RequestBody.create(MEDIA_TYPE, body.toJSONString()));

        Request build = request.url(SUBMERCHANT_PAY_URL).build();

        Response response = client.newCall(build).execute();

        String res = response.body().string();
        log.info("SUBMERCHANT_PAY response {}", res);
        JSONObject jsonObject = JSONObject.parseObject(res);
        String status = jsonObject.getString("status");
        if (status.equals("success")) {
            String prepayId = jsonObject.getString("prepayId");

            //创建微信小程序银联支付
            JSONObject body1 = new JSONObject();
            body1.put("prepayId", prepayId);
            body1.put("openId", user.getOpenid());

            OkHttpClient client1 = new OkHttpClient();
            Request.Builder request1 = new Request.Builder();
            request1 = request1.post(RequestBody.create(MEDIA_TYPE, body1.toJSONString()));

            Request build1 = request1.url(WECHATUNIONPAYBIZSMALL_URL).build();

            Response response1 = client1.newCall(build1).execute();

            String res1 = response1.body().string();
            log.info("WECHATUNIONPAYBIZSMALL response {}", res1);
            JSONObject jsonObject1 = JSONObject.parseObject(res1);
            String status1 = jsonObject1.getString("status");
            if (status1.equals("success")) {
                JSONObject returnJson = new JSONObject();
                returnJson.put("prepayId", prepayId);
                returnJson.put("return", jsonObject1.getJSONObject("args"));
                return returnJson;
            }
            throw new ApiException(-1, String.format("创建微信小程序银联支付失败, %s", jsonObject1.getString("msg")));
        }
        throw new ApiException(-1, "创建银联预支付单失败");
    }

}
